package com.cy.pj.sys.service.realm;

import com.cy.pj.sys.dao.SysMenuDao;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysMenuService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import java.util.Set;

public class ShiroRealm extends /*AuthenticatingRealm*/AuthorizingRealm {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysMenuDao sysMenuDao;




    //获取并封装认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户提交的认证用户信息
        UsernamePasswordToken upToken= (UsernamePasswordToken) authenticationToken;
        //获取用户名
        String username=upToken.getUsername();
        //基于用户名查询用户信息
        SysUser user=sysUserDao.selectUserByUsername(username);
        if(user==null){//用户不存在
            throw new UnknownAccountException();
        }
        if(user.getValid()==0){//用户被禁用
            throw new LockedAccountException();
        }
        //封装用户信息
        ByteSource credentialsSalt=ByteSource.Util.bytes(user.getSalt());
        SimpleAuthenticationInfo info=
                new SimpleAuthenticationInfo(
                        user, //principal 传入的用户身份
                        user.getPassword(),//hashedCredentials
                        credentialsSalt,//credentialsSalt
                        getName());
        return info;
    }

    @Override
    //重写获取凭证加密算法的方法
    public CredentialsMatcher getCredentialsMatcher() {
        HashedCredentialsMatcher matcher=new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(1);
        return matcher;
    }

    @Override
    //获取并封装授权信息
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principalCollection) {
        //1.获取登录用户(登录时传入的用户身份是谁)
        SysUser user= (SysUser) principalCollection.getPrimaryPrincipal();
        //2.基于登录用户 id 获取用户权限标识
        Set<String> stringPermissions=sysMenuDao.selectUserPermissions(user.getId());
        //3.封装数据并返回
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(stringPermissions);
        return info;
    }
}
